package com.ravi.controller;

import com.ravi.common.Constant;
import com.ravi.common.R;
import com.ravi.core.patient.BasePatient;
import com.ravi.core.queue.CheckUpQueue;
import com.ravi.core.queue.HashQueueManager;
import com.ravi.dao.RoomScreenDAO;
import com.ravi.entity.RoomScreen;
import com.ravi.exception.CheckSystemException;
import com.ravi.exception.ErrorCode;
import com.ravi.request.ScreenQueueForm;
import com.ravi.request.ScreenTokenForm;
import com.ravi.util.jwt.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.BlockingQueue;

@RestController
@RequestMapping("screen")
public class ScreenController {

	@Autowired
	private RoomScreenDAO roomScreenDAO;

	@PostMapping("init")
	public R initScreen(@RequestBody ScreenTokenForm form) {
		if (!Objects.equals(form.getSecret(), Constant.SCREEN_SECRET)) {
			throw new CheckSystemException("密钥错误!", ErrorCode.SCREEN_SECRET_ERROR);
		}
		RoomScreen roomScreen = roomScreenDAO.selectByScreenId(form.getId());
		if (roomScreen == null) {
			throw new CheckSystemException("无此显示屏幕记录！",ErrorCode.SCREEN_NOT_FOUND_ERROR);
		}

		Map<String,String> paras = new HashMap<>();
		paras.put("id", String.valueOf(roomScreen.getScreenId()));
		paras.put("roomId", String.valueOf(roomScreen.getRoomId()));
		String token = JWTUtils.getPerpetualToken(paras);
		return R.ok("成功获得永久token!").put("token", token);
	}

	@PostMapping("queue")
	public R getQueue(HttpServletRequest request, @RequestBody ScreenQueueForm form) {
		final Integer roomId = JWTUtils.getRoomId(request.getHeader("token"));
		CheckUpQueue checkUpQueue = HashQueueManager.getQueue(roomId);
		BlockingQueue<BasePatient> mCheckQueue = checkUpQueue.getMCheckQueue();
		Object[] objects = mCheckQueue.toArray();
		List<Object> ret = new ArrayList();
		for (int i = form.getIndex(), temp = 0; i < objects.length; i++) {
			if (temp >= form.getSize()) {
				break;
			}
			ret.add(objects[i]);
			temp++;
		}
		return R.ok().put("queue", ret).put("total", objects.length);
	}

}
